package com.bomberdroid.controller;

import android.graphics.Point;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class GameControls implements OnTouchListener {

	private static final String TAG = GameControls.class.getSimpleName();

	public GameJoystick joystick;
	public GameBombeButton bombeButton;

	// Position du bomberman
	public Point _pointerPosition = new Point(220, 150);

	private MotionEvent lastEvent;
	private boolean bActifJoystick = false;
	private boolean bActifButton = false;
	private boolean seekInactif = false;

	private boolean endGame = false;
	
	private int PIDJoystick;
	private int PIDButton;

	public boolean onTouch(View v, MotionEvent event) {
		// Log.i(TAG, "onTouch " + event.getPointerId(0));
		if(!this.endGame)
			update(event);
		return true;
	}

	public void update(MotionEvent event) {

		/*
		 * Avoids null pointer
		 */
		if (event == null && lastEvent == null) {
			return;
		} else if (event == null && lastEvent != null) {
			event = lastEvent;
		} else {
			lastEvent = event;
		}

		bActifButton = false;
		bActifJoystick = false;

		int action = event.getAction();
		int actionCode = action & MotionEvent.ACTION_MASK;

		for (int i = 0; i < event.getPointerCount(); i++) {
			// Parcourt des points touches

			if (actionCode == MotionEvent.ACTION_DOWN || actionCode == MotionEvent.ACTION_POINTER_DOWN
					|| actionCode == MotionEvent.ACTION_MOVE) {

				Point touch = new Point((int) event.getX(i), (int) event.getY(i));

				if (Math.abs(touch.x - joystick.getOrigine().x) < joystick.getSeuil()
						&& Math.abs(touch.y - joystick.getOrigine().y) < joystick.getSeuil()) {

					bActifJoystick = true;
					PIDJoystick = event.getPointerId(i);
					joystick.onTouchJoystick(touch);

				} else if (Math.abs(touch.x - bombeButton.getOrigine().x) < bombeButton.getSeuil()
						&& Math.abs(touch.y - bombeButton.getOrigine().y) < bombeButton.getSeuil()) {

					bActifButton = true;
					PIDButton = event.getPointerId(i);
					bombeButton.onTouchBombeButton(touch);

				}

			} else if (actionCode == MotionEvent.ACTION_UP || actionCode == MotionEvent.ACTION_POINTER_UP
					|| actionCode == MotionEvent.ACTION_OUTSIDE) {
				if (event.getPointerCount() > 1) {
					// We need to watch the one who is still actif 
					seekInactif = true;

				} else {
					// If there was only one pointer we can inative all the controlers
					bombeButton.inactif();
					joystick.inactif();
				}
			}

			if (seekInactif) {
				if (!bActifButton) {
					seekInactif = false;
					bombeButton.inactif();
				} else if (!bActifJoystick) {
					seekInactif = false;
					joystick.inactif();
				}
			}
		}

	}

	public void setEndGame(boolean endGame) {
		this.endGame = endGame;
		bombeButton.inactif();
		joystick.inactif();
	}

}
